package cqrtplm.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.PageInfo;
import com.hustcad.plm.pdm.flowbusiness.model.entity.WorkFlowObjectPackage;
import com.hustcad.plm.pdm.workflow.controller.TyplmFlowableModelCustomController;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import cqrtplm.constant.RouteConstant;
import cqrtplm.dto.DspfMbomBomDTO;
import cqrtplm.dto.DspfMbomDetailPoiDTO;
import cqrtplm.dto.RtCfgBomDTO;
import cqrtplm.dto.query.BomQueryDTO;
import cqrtplm.entity.DspfMbomDetailDO;
import cqrtplm.entity.RtCfgBomDO;
import cqrtplm.service.RTKnowledgePushService;
import cqrtplm.service.RtCfgBomService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.ty.basic.response.ResponseResult;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@RestController
@Api(tags = "配置系统-需求状态表搭建成品BOM")
@RequestMapping(RouteConstant.RTCFGBUILDBOM + "v1")
public class RtCfgBuildBOMController {

    @Autowired
    private RtCfgBomService rtCfgBomService;
    @Resource
    private RTKnowledgePushService rtKnowledgePushService;
    @Resource
    private TyplmWorkFlowContainerService typlmWorkFlowContainerService;
    @Resource
    private TyplmFlowableModelCustomController typlmFlowableModelCustomController;



    /**
     * 根据父级对象查询并添加他的所有下级对象
     * @param
     * @return
     */
//    @GetMapping("/getRtCfgBuildBOMDetail")
//    public ResponseResult getRtCfgBuildBOMDetail(Long oid,String statuscode) throws JsonProcessingException {
//        return rtCfgBomService.getRtCfgBuildBOMDetail(oid,statuscode);
//    }

    private WorkFlowObjectPackage getWorkFlowObjectPackage(BigInteger toid) {
        WorkFlowContainerView workFlowContainerView = this.typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(toid);
        if (workFlowContainerView == null) {
            return null;
        }

        try {
            return (WorkFlowObjectPackage) workFlowContainerView;
        } catch (ClassCastException e) {
            throw new RuntimeException("对象转换失败", e);
        }
    }

    /**
     * 根据需求流程对象OID主键查询BOM列表
     * @param
     * @return
     */
    @PostMapping("/getRtCfgBuildBOMList")
    public ResponseResult getRtCfgBuildBOMList(@RequestBody BomQueryDTO queryBomDTO){
//        //获取流程对象包
//        WorkFlowObjectPackage workflowobjectPackage = getWorkFlowObjectPackage(new BigInteger(queryBomDTO.getOid()));
//        if (workflowobjectPackage == null) {
//            return ResponseResult.fail("500","没有找到该流程！");
//        }
//        if (workflowobjectPackage.getFlowObjectList() != null &&
//                !workflowobjectPackage.getFlowObjectList().isEmpty() &&
//                workflowobjectPackage.getFlowObjectList().get(0).getOid() != null) {
//            queryBomDTO.setOid(workflowobjectPackage.getFlowObjectList().get(0).getOid().toString());
//        }else {
//            return ResponseResult.fail("500","没有找到该流程对象！");
//        }

        return rtCfgBomService.getRtCfgBuildBOMList(queryBomDTO);
    }

    /**
     * 查询指定库里面没有的物料数据
     * @param queryBomDTO
     * @return
     */
    @PostMapping("/getRtCfgBuildBOMZD")
    public ResponseResult getRtCfgBuildBOMZD(@RequestBody BomQueryDTO queryBomDTO){
        return rtCfgBomService.getRtCfgBuildBOMZD(queryBomDTO);
    }

    /**
     * 替换图样代号或者物料码之前优先进行模组判断
     */
    @GetMapping("/replacePartNumber")
    public ResponseResult replacePartNumber(String partNumber,String oid,String producttype){
        return rtCfgBomService.replacePartNumber(partNumber,oid,producttype);
    }

    /**
     * 根据编码查询物料信息
     * @param
     * @return
     */
    @PostMapping("/getRtCfgBOMByPartNumber")
    public ResponseResult getRtCfgBOMByPartNumber(@RequestBody BomQueryDTO dto){
        return rtCfgBomService.getRtCfgBOMByPartNumber(dto);
    }

    /**
     * 获取图号衍生码
     * @param dto
     * @return
     */
    @PostMapping("/getRtCfgBOMByDrawing")
    public ResponseResult getRtCfgBOMByDrawing(@RequestBody BomQueryDTO dto){
        return rtCfgBomService.getRtCfgBOMByDrawing(dto);
    }


    /**
     * 勾选物料替换图号
     * @param dspfMbomDetailDO
     * @return
     */
    @PostMapping("/updateEbomPartNumberByPartNumber")
    public ResponseResult updateEbomPartNumberByPartNumber(@RequestBody DspfMbomDetailDO dspfMbomDetailDO){
    	return rtCfgBomService.updateEbomPartNumberByPartNumber(dspfMbomDetailDO);
    }
    /**
     * 状态需求表查询文本推送信息
     * @param oid
     * @return
     */
    @GetMapping("/searchStatus-text")
    @ApiOperation(value = "状态需求表查询文本推送信息")
    public ResponseResult searchStatusText(String oid,String currentFlowName) {
        return rtKnowledgePushService.searchStatusText(oid,currentFlowName);
    }


    /**
     * 状态需求表打包下载文件
     * @param oid
     * @return
     */
    @GetMapping("/download-status-files")
    @ApiOperation(value = "状态需求表打包下载文件")
    public ResponseResult<byte[]> downloadStatusFiles(String oid,String currentFlowName) {
        return rtKnowledgePushService.downloadFilesAsZip(oid,currentFlowName);
    }

    /**
     * 成品BOM搭建 todo 此方法用作测试用 后续可删除
     * @param
     * @return
     */
    @GetMapping("/buildBOM")
    public ResponseResult buildBOM(@RequestParam List<DspfMbomDetailDO> list){
        rtCfgBomService.buildBOM(list,"测试成品码",null);
        return ResponseResult.success();
    }


    /**
     * 根据需求状态表的工厂配置将生成BOM转为相关的工厂视图
     */
     @GetMapping("/generateBOMToFactoryView")
    public ResponseResult generateBOMToFactoryView(String partOid,String viewRefName,String viewDefOid){
         return rtCfgBomService.generateBOMToFactoryView(partOid,viewRefName,viewDefOid);
     }

    /**
     * 手动调整机组动力结构
     */
    @PostMapping("/manualAdjustmentOfGroupPowerStructure")
    public ResponseResult manualAdjustmentOfGroupPowerStructure(@RequestBody RtCfgBomDTO rtCfgBomDTO){
        return rtCfgBomService.manualAdjustmentOfGroupPowerStructure(rtCfgBomDTO);
    }

    /**
     * BOM保存
     */
    @PostMapping("/saveBOM")
    public ResponseResult saveBOM(@RequestBody List<DspfMbomBomDTO> dtos){
        return rtCfgBomService.saveBOM(dtos);
    }


    /**
     * 获取流程模板所有节点的名称
     * @param templateName
     * @return
     */
    @GetMapping("/getWorkFlowName")
    public ResponseResult getWorkFlowName(String templateName) {
        return rtCfgBomService.getWorkFlowName(templateName);
    }


    /**
     * 下载导出模版
     * @param response
     * @throws IOException
     */
    @ApiOperation("下载导出模版")
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 创建一个空的模板数据
        List<DspfMbomDetailPoiDTO> dataList = new ArrayList<>();
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("BOM导入模板", "BOM导入模板"), DspfMbomDetailPoiDTO.class, dataList);

        // 设置响应头，指定下载文件名
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=bom_template.xlsx");

        // 输出模板文件到浏览器
        workbook.write(response.getOutputStream());
        workbook.close();
    }

    /**
     * 导入BOM结构数据
     * @param file
     * @return
     * @throws Exception
     */
    @ApiOperation("导入")
    @PostMapping("/import")
    public ResponseResult importExcel(@RequestParam("file") MultipartFile file,
                                      @RequestParam("bomid") String bomid) throws Exception {
        return rtCfgBomService.importExcel(file,bomid);
    }

}
